package edu.metrostate.capstonediner;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.res.AssetManager;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;

public class GameRenderer implements Renderer {
	// Stores the view that allows us to draw via OpenGL ES
	private GLSurfaceView glView;
	// Stores the assent manager used to load textures
	private AssetManager assetManager;
	// Stores the DrawableParts
	private PartBuffer parts;
	// Stores the DrawableTexts
	private TextBuffer texts;
	
	/**
	 * Creates and initializes the GameRenderer
	 * 
	 * @param game The GameActivity
	 */
	public GameRenderer(Controller game) {
		glView = game.getView();
		glView.setEGLConfigChooser(8, 8, 8,8,16,0);
		assetManager = game.getAssetManager();
		
		parts = new PartBuffer();
		texts = new TextBuffer();
	}
	
	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // Loads the game's textures
		parts.setTexture(new PartTexture(assetManager, gl, Constants.PART_TEXTURE_FILENAME));
		texts.setTexture(new FontTexture(assetManager, gl, Constants.FONT_TEXTURE_FILENAME));
	}
	
	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
	}
	
	@Override
	public void onDrawFrame(GL10 gl) {
		gl.glClearColor(0, 0, 0, 1);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		gl.glViewport(0, 0, glView.getWidth(), glView.getHeight());
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		// use a 3:4 aspect ration
		gl.glOrthof(0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT, 0, 1, -1);
		
		// Enables alpha blending
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		
		// Enables textures
		gl.glEnable(GL10.GL_TEXTURE_2D);
		
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		parts.onDrawFrame(gl);
		texts.onDrawFrame(gl);
	}
	
	public void add(DrawablePart part) {
		parts.add(part);
	}
	
	public void add(DrawableText text) {
		texts.add(text);
	}
	
	public void remove(DrawablePart part) {
		parts.remove(part);
	}
	
	public void remove(DrawableText text) {
		texts.remove(text);
	}
	
	public void update() {
		parts.update();
		texts.update();
	}
}
